package com.example.clientend.config;

import com.alibaba.fastjson.JSONObject;
import com.example.clientend.domain.MqttMsg;
import com.example.clientend.utils.InfoGetter;
import com.example.clientend.utils.MqttHandler;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

/**
 * MQTT回调函数配置类
 */
@Configuration
@Slf4j
public class MqttCallbackConfig implements MqttCallback, MqttCallbackExtended {
    @Autowired
    MqttHandler mqttHandler;
    @Autowired
    InfoGetter infoGetter;
    
    @Value("${mqtt.topic.subscribeTopic}")
    private String subscribeTopic;

    /**
     * 
     * 客户端连接成功的回调
     * 客户端掉线重连后需要重新手动订阅主题
     * 设置连接成功后自动订阅主题，使客户端掉线自动重连后能继续收到对应主题的消息
     */
    @Override
    public void connectComplete(boolean isSuccess, String message) {
        System.out.println("MQTT客户端连接成功！");
        System.out.println("订阅主题：" + subscribeTopic);
        MqttConfig.subscribe(subscribeTopic,0);
    }

    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("与服务器断开连接，即将自动重连");
    }

    /**
     * 消息到达的回调
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println(String.format("从主题%s接收到消息！",topic));
        // 将消息体转换为JSONString后再转换为MqttMsg类，提取出deviceClientId和instruction
        MqttMsg mqttMsg = JSONObject.parseObject(new String(message.getPayload()), MqttMsg.class);
        // 读取本机deviceClientId，判断该MQTT指令是否是向本机发起的
        JSONObject deviceInfo = infoGetter.getDeviceInfo();
        String clientId = (String) deviceInfo.get("deviceClientId");
        if (mqttMsg.getDeviceClientId().equals(clientId)) {
            log.info("接收到主控端的MQTT信息：" + mqttMsg);
            // 根据收到的instruction进行处理
            mqttHandler.handlerMqttInstruction(mqttMsg.getInstruction());
        }
    }

    /**
     * 消息发布成功的回调
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println(String.format("MQTT消息发布成功"));
    }
}
